// 报表管理模块
import java.awt.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Vector;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Dataform {
	public static JPanel dataformJPanel = null; 
	public static void init() {
		// 初始化报表管理模块，使用竖向布局，并添加组件。
		dataformJPanel = new JPanel();
		dataformJPanel.setLayout(new BoxLayout(dataformJPanel, BoxLayout.Y_AXIS));
		// 添加标题
		dataformJPanel.add(new JLabel("报表管理模块"));
		// 添加立即刷新数据按钮
		JButton refreshData = new JButton("立即刷新数据");
		dataformJPanel.add(refreshData);
		// 添加文本标签，显示基础数据 本月收益 物品消耗 平均入住比例等数据信息
		JLabel baseData = new JLabel("近期收益：N/A");
		JLabel averageStay = new JLabel("入住比例：N/A");
		dataformJPanel.add(baseData);
		dataformJPanel.add(averageStay);
		// 添加两个按钮，可用查看详细账单和消耗表数据
		JButton detailBill = new JButton("查看详细账单");
		dataformJPanel.add(detailBill);
		// 刷新指令，点击按钮后执行刷新操作
		refreshData.addActionListener(e -> {
			try {
				Statement stmt = Main.conn.createStatement();
				// 将billing累计
				ResultSet rs = stmt.executeQuery("SELECT SUM(HotelSysteam.Checkout.billing) AS TotalIncome FROM HotelSysteam.Checkout WHERE Date > DATE_SUB(CURDATE(), INTERVAL 1 MONTH);");
				if (rs.next()) {
					// 保留两位小数，并显示近期收益
					baseData.setText("近期收益：" + String.format("%.2f", rs.getDouble("TotalIncome")));
				}
				else {
					// 弹窗提示无数据
					JOptionPane.showMessageDialog(null, "近期无首页数据！");
					baseData.setText("近期收益：N/A");
				}
				// 释放资源
				rs.close();
				// 访问入住比例，执行SELECT (SUM(CASE WHEN HotelSysteam.lodging.Date IS NULL THEN 0 ELSE 1 END) * 100.0 / COUNT(*)) AS null_percentage FROM HotelSysteam.Room LEFT OUTER JOIN HotelSysteam.lodging ON HotelSysteam.Room.ID = HotelSysteam.lodging.RoomID ORDER BY Room.ID;
				// 即可获取入住比例
				rs = stmt.executeQuery("SELECT (SUM(CASE WHEN HotelSysteam.lodging.Date IS NULL THEN 0 ELSE 1 END) * 100.0 / COUNT(*)) AS null_percentage FROM HotelSysteam.Room LEFT OUTER JOIN HotelSysteam.lodging ON HotelSysteam.Room.ID = HotelSysteam.lodging.RoomID ORDER BY Room.ID;");
				if (rs.next()) {
					// 保留一位小数，并显示入住比例
					averageStay.setText("当前入住比例：" + String.format("%.1f", rs.getDouble("null_percentage")) + "%");
				}else
				{
					// 理论不会出现这种情况，万一出现则弹出警告
					JOptionPane.showMessageDialog(null, "疑似获取过程出现错误！");
					averageStay.setText("当前入住比例：N/A");
				}
				rs.close();
				stmt.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		});
		// 查看详细账单按钮，点击后弹出窗口显示详细账单信息
		detailBill.addActionListener(e -> {
			showCheckoutRecord(); // 调用查看退房记录的方法
		});

	}
	// 弹出退房记录窗口
	public static void showCheckoutRecord() {
		// 弹出退房记录窗口，提供查询指定房间.用户.日期范围.客户身份证号码
		JFrame frame = new JFrame("退房记录查询");
		frame.setSize(800, 600);
		// 使用纵向布局，添加查询面板和表格显示区域


		// 添加查询面板和表格显示区域到窗口
		JPanel searchPanel = new JPanel();
		searchPanel.add(new JLabel("房间："));
		JTextField roomIDField = new JTextField(10);
		searchPanel.add(roomIDField);
		searchPanel.add(new JLabel("姓名："));
		JTextField userNameField = new JTextField(10);
		searchPanel.add(userNameField);
		searchPanel.add(new JLabel("日期"));
		JTextField dateRangeField = new JTextField(10);
		searchPanel.add(dateRangeField);
		searchPanel.add(dateRangeField);
		// 上一天和下一天按钮
		JButton prevDay = new JButton("上一天");
		searchPanel.add(prevDay);
		JButton nextDay = new JButton("下一天");
		searchPanel.add(nextDay);
		// 查询按钮
		JButton search = new JButton("查询");
		searchPanel.add(search);
		// 添加输出面板，用于显示查询结果，表格形式
		// 包含身份证号码 用户名 房号 退房时间 退房日期 赔付金额 应付金额字段
		// 对应IDcard UserName RoomID Time Date Reparations billing字段

		// 创建表格 支持滚动条
		DefaultTableModel a = new DefaultTableModel(new String[] { "身份证号码", "用户名", "房号", "退房时间", "退房日期", "赔付金额", "应付金额" }, 0);
		JTable table = new JTable(a);
		JScrollPane scrollPane = new JScrollPane(table);
		frame.add(searchPanel, BorderLayout.NORTH);
		frame.add(scrollPane, BorderLayout.CENTER);
		frame.setVisible(true);
		// 日期对话框设置为当前日期，并允许用户选择范围
		dateRangeField.setText(java.time.LocalDate.now().toString());
		// 上一天按钮点击事件，更新日期范围字段为前一天的日期
		prevDay.addActionListener(e -> {
			System.out.println("上一天按钮被点击");
			// 获取当前日期范围字段的值，并将其减去1天
			String currentDateRange = dateRangeField.getText();
			if (!currentDateRange.isEmpty()) {
				try {
					java.time.LocalDate localDate = java.time.LocalDate.parse(currentDateRange);
					localDate = localDate.minusDays(1);
					dateRangeField.setText(localDate.toString());
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(null, "请输入正确的日期格式！");
				}
			}
		});
		nextDay.addActionListener(e -> {
			System.out.println("下一天按钮被点击");
			// 获取当前日期范围字段的值，并将其加上1天
			String currentDateRange = dateRangeField.getText();
			if (!currentDateRange.isEmpty()) {
				try {
					java.time.LocalDate localDate = java.time.LocalDate.parse(currentDateRange);
					localDate = localDate.plusDays(1);
					dateRangeField.setText(localDate.toString());
				} catch (Exception ex) {
					JOptionPane.showMessageDialog(null, "请输入正确的日期格式！");
				}
			}
		});


		// 查询按钮点击事件，执行查询操作并更新表格数据
		search.addActionListener(e -> {
			System.out.println("查询按钮被点击");
			try {
				String roomID = roomIDField.getText();
				String userName = userNameField.getText();
				String dateRange = dateRangeField.getText();
				Statement stmt = Main.conn.createStatement();
				ResultSet rs = null;
				// 判断查询条件，因为是人工输入所以需要模糊查询

				if (!roomID.isEmpty() && !userName.isEmpty() && !dateRange.isEmpty()) {
					System.out.println("查询条件：房间：" + roomID + " 姓名：" + userName + " 日期范围：" + dateRange);
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout WHERE RoomID LIKE '%" + roomID + "%' AND UserName LIKE '%" + userName + "%' AND Date LIKE '%" + dateRange + "%'");
				} else if (!roomID.isEmpty() && !userName.isEmpty()) {
					System.out.println("查询条件：房间：" + roomID + " 姓名：" + userName);
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout WHERE RoomID LIKE '%" + roomID + "%' AND UserName LIKE '%" + userName + "%'");
				} else if (!roomID.isEmpty() && !dateRange.isEmpty()) {
					System.out.println("查询条件：房间：" + roomID + " 日期：" + dateRange);
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout WHERE RoomID LIKE '%" + roomID + "%' AND Date LIKE '%" + dateRange + "%'");
				} else if (!userName.isEmpty() && !dateRange.isEmpty()) {
					System.out.println("查询条件：姓名：" + userName + " 日期：" + dateRange);
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout WHERE UserName LIKE '%" + userName + "%' AND Date LIKE '%" + dateRange + "%'");
				} else if (!roomID.isEmpty()) {
					System.out.println("查询条件：房间：" + roomID);
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout WHERE RoomID LIKE '%" + roomID + "%'");
				} else if (!userName.isEmpty()) {
					System.out.println("查询条件：姓名：" + userName);
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout WHERE UserName LIKE '%" + userName + "%'");
				} else if (!dateRange.isEmpty()) {
					System.out.println("查询条件：日期范围：" + dateRange);
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout WHERE Date LIKE '%" + dateRange + "%'");

					
				} else
				{
					System.out.println("查询条件：无");
					rs = stmt.executeQuery("SELECT * FROM HotelSysteam.Checkout");
				}
				// 更新表格数据
				// 动态数组存储数据
				ArrayList<Object[]> data = new ArrayList<>();
				int count = 0;// 计数器，记录查询到的数据条数

				while (rs.next()) {
					count++; // 查询到的数据条数加一
					// 逐个读取记录，并添加到表格中
					String IDcard = rs.getString("IDcard");
					String UserName = rs.getString("UserName");
					String RoomID = rs.getString("RoomID");
					String Time = rs.getString("Time");
					String Date = rs.getString("Date");
					double Reparations = rs.getDouble("Reparations");
					double billing = rs.getDouble("billing");
					// 添加
					data.add(new Object[] { IDcard, UserName, RoomID, Time, Date, Reparations, billing });
				}
				System.err.println("查询到数据条数：" + count);
				// 更新表格内容
				// 先重新创建一个表格
				DefaultTableModel model = new DefaultTableModel(new String[] { "身份证号码", "用户名", "房号", "退房时间", "退房日期", "赔付金额", "应付金额" }, 0);
				for (Object[] row : data) {
					model.addRow(row);
				}
				table.setModel(model); // 设置表格模型为新的数据模型
				// 更新表格显示
				frame.revalidate(); // 重绘窗口以显示更新后的内容
				frame.repaint(); // 重画窗口以显示更新后的内容
				rs.close();
				stmt.close();
			} catch (SQLException e1) {
				System.out.println("查询出错");
				e1.printStackTrace();
			} 
		});
		// 显示窗口
		frame.add(searchPanel);
		frame.setVisible(true);
	}
}